package com.MC.MCard.dao;

import com.MC.MCard.entity.Merchant;
import com.MC.MCard.utils.DataSourceManager;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.management.Query;
import java.sql.SQLException;

public class MerchantDaoImpl {

    private QueryRunner runner = new QueryRunner(DataSourceManager.getDataSource());

    public Merchant findByEmail(String memail) {
        String sql = "SELECT M_ID,M_NAME,M_EMAIL,M_PSWD FROM merchant WHERE memai=?";
        try {
            return runner.query(sql, new BeanHandler<Merchant>(Merchant.class), memail);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public Merchant findById(int mid) throws SQLException {
        String sql = "SELECT M_ID,M_NAME,M_EMAIL,M_PSWD FROM merchant WHERE mid=? ";
        return runner.query(sql, new BeanHandler<Merchant>(Merchant.class), mid);

    }
    public long insert(String memail, String mname, String mpassword) {
        String sql = "INSERT INTO merchant(M_ID,M_NAME,M_EMAIL,M_PSWD  VALUES(?,?,?,?)";
        try {
            return (long) runner.insert(sql, new ScalarHandler<>(),memail ,mname ,mpassword);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return -1;
    }

    public int delete(int mid) throws SQLException {
        String sql = "DELETE FROM merchant WHERE M_ID=?";
        return runner.update(sql, mid);
    }

    public int update(int mid, String memail, String mname, String mpassword) throws SQLException {
        String sql = "UPDATE merchant SET M_ID=?,M_NAME=?,M_EMAIL=?,M_PSWD=? WHERE M_ID=? ";
        return runner.update(sql, mid, mname,memail,mpassword);
    }
}
